from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from ....api import deps
from ....core import security
from ....core.config import settings
from ....schemas.auth import Token, Login, LoginResponse
from ....crud.user import user_crud
from ....crud.counselor import counselor_crud
from ....schemas.user import UserCreate
from ....schemas.counselor import CounselorCreate
from ....crud.student import student_crud
from ....schemas.student import StudentCreate

router = APIRouter()

@router.post("/login", response_model=LoginResponse)
def login(
        login_data: Login,
        db: Session = Depends(deps.get_db)
):
    """
    使用学号和密码获取访问令牌
    """
    user = user_crud.authenticate(
        db, account_id=login_data.account_id, password=login_data.password
    )
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="学号或密码不正确",
            headers={"WWW-Authenticate": "Bearer"},
        )
    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户未激活"
        )

    # 创建访问令牌
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = security.create_access_token(
        user.id, expires_delta=access_token_expires
    )

    return {
        "access_token": access_token,
        "token_type": "bearer",
        "user_id": user.id,
        "role": user.role
    }

@router.post("/register", response_model=Token)
def register(
        request_body: dict,
        db: Session = Depends(deps.get_db)
):
    """
    创建新用户
    """
    # 从请求体中提取数据
    user_data = UserCreate(**request_body["user_data"])

    # 检查学号是否已注册
    if user_data.account_id and user_crud.get_by_account_id(db, account_id=user_data.account_id):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该学号已被注册",
        )

    # 检查邮箱是否已注册
    if user_data.email and user_crud.get_by_email(db, email=user_data.email):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该邮箱已被注册",
        )

    # 检测手机号是否已注册
    if user_data.phone_number and user_crud.get_by_phone_number(db, phone_number=user_data.phone_number):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该手机号已被注册",
        )

    try:
        # 创建用户
        user = user_crud.create(db, obj_in=user_data)

        # 根据角色创建对应记录
        if user.role == "student" and "student_data" in request_body:
            student_data = StudentCreate(
                **request_body["student_data"]
            )
            student_crud.create_with_user(db, user_id=user.id, obj_in=student_data)
            import logging; logging.info(f"学生记录创建成功，ID: {user.id}")

        elif user.role == "counselor" and "counselor_data" in request_body:
            counselor_data = CounselorCreate(
                **request_body["counselor_data"]
            )
            counselor_crud.create_with_user(db, user_id=user.id, obj_in=counselor_data)
            import logging; logging.info(f"辅导员记录创建成功，ID: {user.id}")
    except Exception as e:
        # 如果角色信息创建失败，回滚用户创建
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"注册失败：{str(e)}"
        )
    # 创建访问令牌
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = security.create_access_token(
        user.id, expires_delta=access_token_expires
    )

    return {
        "access_token": access_token,
        "token_type": "bearer",
        "user_id": user.id  # 添加user_id与登录响应保持一致
    }